<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="box-card">
      <!-- 卡片的内容区域 -->
      <!--
          搜索和添加的视图
            row     一行
            col     一行里面的一列
            gutter  列之间的间距
            span    列的宽度
      -->
      <el-row :gutter="20">
        <!-- 搜索区域
              input
              clearable   可清空input
        -->
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="userInfo.query" clearable @clear="clearSearch">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <!-- 添加用户 -->
        <el-col :span="16">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!--
          table数据的渲染
            data   表格需要渲染的数据
            prop   这一列需要渲染对象的键
            label  这一列的列名
            border 给表格添加竖向的边框
            stripe 表格隔行变色
            width  指定列的宽度
            注：某一列的不是数据项，可能是删除或修改，需要使用作用域插槽拿到这一列的数据
      -->
      <el-table :data="userList" style="width: 100%" border stripe>
        <!-- 实现我们列的索引值 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="用户"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="changeUserState(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <!-- 使用插槽拿到当前行的数据 -->
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editUser(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row.id)"
            ></el-button>
            <!--
              placement  提示文字的位置
              enterable  鼠标是否进入提示文字
            -->
            <el-tooltip content="分配角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="allotRolesList(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 用户列表的分页
          size-change      每页的条数改变触发的事件
          current-change   当前页改变时触发的事件
          current-page     当前的页码
          page-sizes       每页条数的数组
          page-size        每页有几条数据
          total            总条数
      -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="userInfo.pagenum"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="userInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClose">
      <!-- 对话框的内容区域 -->
      <el-form :model="addRuleForm" :rules="addRules" ref="addRuleForm" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addRuleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addRuleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addRuleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addRuleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框的按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addDialogUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户的对话框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClose">
      <el-form :model="editRuleForm" :rules="editRules" label-width="70px" ref="editRuleForm">
        <el-form-item label="用户名">
          <el-input v-model="editRuleForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editRuleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editRuleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editDialogUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色 -->
    <el-dialog title="分配角色" :visible.sync="allotdialogVisible" width="50%" @close="allotClose">
      <div class="mb">当前用户：{{roleInfo.username}}</div>
      <div class="mb">当前角色：{{roleInfo.role_name}}</div>
      <div>
        <el-form :model="roleInfo" :rules="allotRules" ref="allotFormRef">
          <el-form-item label="分配角色:" prop="rid">
            <el-select v-model="roleInfo.rid" placeholder="请选择">
              <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="allotdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRole">确 定</el-button>
      </span>

    </el-dialog>
  </div>
</template>

<script>
import {
  getUserList,
  editUserState,
  addUser,
  searchUser,
  editUser,
  delUser,
  getRolesList,
  allotRole
} from '../../api/user'
export default {
  data () {
    var checkEmail = (rule, val, cb) => {
      var emailReg = /^([a-zA-Z]|[0-9])(\w|-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
      if (!emailReg.test(val)) return cb(new Error('请填写正确的邮箱账号'))
      cb()
    }
    var checkMobile = (rule, val, cb) => {
      var emailReg = /^1[3456789]\d{9}$/
      if (!emailReg.test(val)) return cb(new Error('请填写正确的手机号'))
      cb()
    }
    return {
      // 用户列表的数据
      userList: [],
      // 请求的参数
      userInfo: {
        // 查询的参数
        query: '',
        // 查询的当前页码
        pagenum: 1,
        // 每页的条数
        pagesize: 2
      },
      // 用户的总条数
      total: 0,
      // 添加对话框的显示或隐藏
      addDialogVisible: false,
      // 添加用户的信息
      addRuleForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户的验证规则
      addRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editDialogVisible: false,
      editRuleForm: {
        username: '',
        email: '',
        mobile: ''
      },
      editRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 控制分配角色的对话框
      allotdialogVisible: false,
      // 分配角色信息
      roleInfo: {
        id: '',
        rid: '',
        username: '',
        role_name: ''
      },
      // 角色列表
      rolesList: [],
      allotRules: {
        rid: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
      }
    }
  },
  created () {
    this.userInfo = this.$store.getters.getUserInfo
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await getUserList(this.userInfo)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.userList = res.data.users
      this.total = res.data.total
      console.log(res)
    },
    // 每页的条数改变触发的函数
    handleSizeChange (newSize) {
      this.userInfo.pagesize = newSize
      this.$store.commit('SAVE_USER_INFO', this.userInfo)
      this.getUserList()
    },
    // 当前页改变时触发的函数
    handleCurrentChange (curPage) {
      this.userInfo.pagenum = curPage
      this.$store.commit('SAVE_USER_INFO', this.userInfo)
      this.getUserList()
    },
    // 清除搜素条件时触发的对象
    clearSearch () {
      this.$store.commit('SAVE_USER_INFO', this.userInfo)
      this.getUserList()
    },
    // 改变用户的状态
    async changeUserState (row) {
      const { data: res } = await editUserState(row.id, row.mg_state)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getUserList()
    },
    // 添加对话框关闭的时候执行的函数
    addDialogClose () {
      this.$refs.addRuleForm.resetFields()
    },
    // 添加用户
    addDialogUser () {
      this.$refs.addRuleForm.validate(async validate => {
        if (!validate) return
        const { data: res } = await addUser(this.addRuleForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getUserList()
        this.addDialogVisible = false
      })
    },
    editDialogClose () {
      this.$refs.editRuleForm.resetFields()
    },
    async editUser (id) {
      const { data: res } = await searchUser(id)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editRuleForm = res.data
      this.editDialogVisible = true
    },
    editDialogUser () {
      this.$refs.editRuleForm.validate(async validate => {
        if (!validate) return
        const { data: res } = await editUser(
          this.editRuleForm.id,
          this.editRuleForm
        )
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getUserList()
        this.editDialogVisible = false
      })
    },
    async deleteUser (id) {
      var result = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (result === 'cancel') return this.$message.info('已取消删除')
      const { data: res } = await delUser(id)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      if (res.meta.status === 400) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getUserList()
    },
    // 分配权限
    async allotRolesList (user) {
      this.roleInfo.username = user.username
      this.roleInfo.role_name = user.role_name
      this.roleInfo.id = user.id
      const { data: res } = await getRolesList()
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rolesList = res.data
      this.allotdialogVisible = true
      console.log(res)
    },
    allotRole () {
      this.$refs.allotFormRef.validate(async validate => {
        if (!validate) return
        const { data: res } = await allotRole(this.roleInfo.id, this.roleInfo.rid)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getUserList()
        this.allotdialogVisible = false
        console.log(res)
      })
    },
    allotClose () {
      this.$refs.allotFormRef.resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
.mb {
  margin-bottom: 10px;
  padding-left: 10px;
}
</style>
